package hk.linkcredit.awardservice.award.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import hk.linkcredit.awardservice.common.constant.SmsSendConfig;
import hk.linkcredit.awardservice.award.domain.vo.SmsSendData;
import hk.linkcredit.awardservice.award.domain.entity.SmsTemplate;
import hk.linkcredit.awardservice.award.service.ISmsTemplateService;
import hk.linkcredit.awardservice.utils.SmsSignUtil;
import hk.linkcredit.awardservice.utils.SmsUtil;
import hk.linkcredit.awardservice.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;


/**
 * @author cyh
 * @date 2022/7/8 6:26 下午
 */
@Slf4j
@Service
public class AwardSmsService {

    @Autowired
    private SmsSendConfig smsSendConfig;

    @Autowired
    private ISmsTemplateService smsTemplateService;

    public static String PARAM_MARK = "#";

    private SmsSignUtil smsSignUtil = new SmsSignUtil();

    private SmsUtil smsUtil = new SmsUtil();


    @Async
    public void asyncSend(SmsSendData smsData) {
        log.info("AwardSmsSend:{}", sendSms(smsData));
    }


    public int sendSms(SmsSendData smsData) {
        int responseCode = -1;
        if (StringUtils.isEmpty(smsData.getContent())) {
            String content = this.getSmsContnet(smsData);
            smsData.setContent(content);
        }
        log.info("将要发送的短信内容为：{}", smsData.getContent());

        //发送短信规则
//        SmsAreaNumberConfigVO smsAreaNumberConfig = smsMapper.getSmsAreaNumberConfig(smsData.getPhoneNumber().substring(0, 4));
//        return super.sendSMSImpl(smsData, smsAreaNumberConfig);
        try {
//            responseCode = sendSmsByRule(smsData);
            JSONObject jsonObject = smsSignUtil.encryptBASE64(smsData.getTmplateId());
            JSONObject data = new JSONObject();
            data.put("phoneNumber", smsData.getPhoneNumber());
            data.put("noticeType", smsData.getNoticeType());
            data.put("verifyCode", smsData.getVerifyCode());
            data.put("content", smsData.getContent());
            data.put("smsType", smsData.getSmsType());
            data.put("smsParam", smsData.getSmsParam());
            data.put("templateId", smsData.getTmplateId());
            jsonObject.put("data", data);
            log.info("send sms request: " + JSON.toJSONString(jsonObject));
            String result = smsUtil.sendPost(smsSendConfig.getSendSms(), jsonObject, null);
            log.info("--------- send sms  :" + result);
            JSONObject json = JSONObject.parseObject(result);
            if (null != json && json.containsKey("code")) {
                responseCode = json.getInteger("code");
            }
        } catch (Exception e) {
            throw new RuntimeException("Fail");
        }
        return responseCode;
    }

    public String getSmsContnet(SmsSendData smsData) {
        SmsTemplate smsTemplate = new SmsTemplate();
        smsTemplate.setNoticeType(smsData.getNoticeType());
        smsTemplate.setSmsType(smsData.getSmsType());
        smsTemplate.setState("1");
        List<SmsTemplate> smsTemplateList = smsTemplateService.selectSmsTemplateList(smsTemplate);
        String content = smsTemplateList.get(0).getTemplateContent();

        if (content.contains(PARAM_MARK)) {
            content = replaceTemplateParams(content, smsData.getSmsParam());
        }

        return content;
    }


    public static String replaceTemplateParams(String templateContent, JSONObject dataJson) {
        String smsContent = templateContent;

        Iterator<String> iterator = (Iterator<String>) dataJson.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            String value = dataJson.getString(key);
            if (smsContent.contains(key)) {
                smsContent = smsContent.replace(PARAM_MARK + key + PARAM_MARK, value);
            }
        }
        return smsContent;
    }


}
